package com.benz.project.pvm.util;

import com.benz.project.pvm.annotation.FieldName;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

/**
 * Bean转换工具类
 *
 * @author lanh
 */
public class BeanConvertUtil {

    /**
     * map转成实体类
     * @param map
     * @param beanClass
     * @return
     * @throws Exception
     */
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;

        Object obj = beanClass.newInstance();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();

            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                continue;
            }

            String fieldColumnName ;
            if(field.isAnnotationPresent(FieldName.class)){
                FieldName fieldName = field.getAnnotation(FieldName.class);
                fieldColumnName = fieldName.value();
            }else{
                fieldColumnName = field.getName();
            }

            field.setAccessible(true);
            field.set(obj, map.get(fieldColumnName));
        }

        return obj;
    }
}
